package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.common.BaseContext;
import com.chen.entity.ShoppingCart;
import com.chen.mapper.ShoppingCartMapper;
import com.chen.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Override
    public List<ShoppingCart> shoppingCartList(Long userId) {
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        return list(lqw);
    }

    @Override
    public ShoppingCart addSC(ShoppingCart shoppingCart) {
        //设置用户id，指定当前是哪个用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        //添加到购物车的是菜品
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userId);
        //添加到购物车的是套餐
        lqw.eq(dishId != null, ShoppingCart::getDishId, dishId);
        //查询当前菜品或者套餐是否在购物车中
        lqw.eq(setmealId != null, ShoppingCart::getSetmealId, setmealId);
        ShoppingCart one = getOne(lqw);
        //如果已经存在，就在原来数量基础上加一
        if (one != null) {
            Integer number = one.getNumber() + 1;
            one.setNumber(number);
            updateById(one);
        } else {
            //如果不存在，则添加到购物车，数量默认就是一
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            save(shoppingCart);
            one = shoppingCart;
        }
        return one;
    }

    @Override
    public void clean() {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(userId != null, ShoppingCart::getUserId, userId);
        remove(lqw);
    }

    @Override
    public void sub(ShoppingCart shoppingCart) {
        Long userId = BaseContext.getCurrentId();
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dishId != null, ShoppingCart::getDishId, dishId);
        lqw.eq(setmealId != null, ShoppingCart::getSetmealId, setmealId);
        lqw.eq(ShoppingCart::getUserId, userId);
        ShoppingCart one = getOne(lqw);

        if (one.getNumber() == 1) {
            remove(lqw);
        } else {
            Integer number = one.getNumber() - 1;
            one.setNumber(number);
            updateById(one);
        }

    }
}
